package controllers

import (
	"github.com/gin-gonic/gin"
	"log"
	"rongyy/src/models"
	"rongyy/src/server"
	"rongyy/src/service"
	"strconv"
)

type CompetitionController struct {
	*service.CompetitionService
}

func NewCompetitionController() *CompetitionController {
	return &CompetitionController{}
}

func (rc *CompetitionController) create(c *gin.Context) server.IModel {
	//log.Println("decode: ", c.MustGet("merchant_id").(string))
	var merchantId int64 = 0

	str, ok := c.Get("merchant_id")
	log.Println("okokok: ", ok)
	if ok {
		val, ojbk := str.(int64)
		log.Println("merchantId1122: ", ojbk)
		if ojbk {
			log.Println("merchantId11: ", merchantId)
			merchantId = val
		}
	}

	json := &models.CompetitionModel{}
	err := c.ShouldBindJSON(json)
	log.Println("merchantId: ", merchantId)
	json.MerchantId = merchantId
	err = rc.Create(json)
	if err != nil {
		log.Println("decode: ", err)
	}
	if err != nil {
		return &models.DataModel{IsSuccess: false, Msg: err.Error()}
	}

	return &models.DataModel{IsSuccess: true, Msg: "报价成功"}
}

func (rc *CompetitionController) query(c *gin.Context) server.IModel {
	limit := c.Query("limit")
	limitInt, err := strconv.Atoi(limit)
	offset := c.Query("offset")
	offsetInt, err := strconv.Atoi(offset)
	json := &models.ReqCompetitionQuery{}
	err = c.ShouldBindJSON(json)
	json.Limit = limitInt
	json.Offset = offsetInt
	data, total, err := rc.QueryByOrder(json)
	if err != nil {
		log.Println("decode: ", err)
	}
	if err != nil {
		return &models.DataModel{IsSuccess: false, Msg: err.Error()}
	}

	return &models.DataModel{IsSuccess: true, Data: map[string]interface{}{
		"list":  data,
		"total": total,
	}, Msg: "查询成功"}
}

func (rc *CompetitionController) accept(c *gin.Context) server.IModel {
	json := &models.CompetitionModel{}
	err := c.ShouldBindJSON(json)
	err = rc.Accept(json)
	if err != nil {
		log.Println("decode: ", err)
	}
	if err != nil {
		return &models.DataModel{IsSuccess: false, Msg: err.Error()}
	}
	return &models.DataModel{IsSuccess: true, Msg: "接受成功"}
}

func (u *CompetitionController) RouterHandler(server *server.Server) {
	server.Handle("POST", "/offer", u.create)
	server.Handle("POST", "/list", u.query)
	server.Handle("POST", "/accept", u.accept)
}
